package com.shkco.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shkco.basic.exception.BusinessException;
import com.shkco.basic.jwt.JwtUtils;
import com.shkco.basic.jwt.LoginData;
import com.shkco.basic.jwt.RsaUtils;
import com.shkco.basic.util.AjaxResult;
import com.shkco.basic.util.HttpUtil;
import com.shkco.basic.util.Md5Utils;
import com.shkco.basic.util.StrUtils;
import com.shkco.system.domain.Menu;
import com.shkco.system.domain.Permission;
import com.shkco.system.mapper.MenuMapper;
import com.shkco.system.mapper.PermissionMapper;
import com.shkco.user.constants.WxConstants;
import com.shkco.user.domain.Logininfo;
import com.shkco.user.domain.User;
import com.shkco.user.domain.Wxuser;
import com.shkco.user.dto.LoginDto;
import com.shkco.user.mapper.LogininfoMapper;
import com.shkco.user.mapper.UserMapper;
import com.shkco.user.mapper.WxuserMapper;
import com.shkco.user.service.ILogininfoService;
import com.shkco.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.通过account和type去查数据库 - Logininfo对象
        Logininfo logininfo = logininfoMapper.accountLogin(loginDto);
        //2.判断Logininfo对象为null - 账号错误 - 抛异常
        if (logininfo == null){
            throw new BusinessException("账号不存在！请重新输入！");
        } else {
            //3.不为null - 判断密码（将md5（密码+盐值） 和  Logininfo对象的密码进行对象）
            //3.1.密码失败  - 抛异常
            String md5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if (!md5Pwd.equals(logininfo.getPassword())){
                throw new BusinessException("密码错误！请重新输入！");
            } else {

                /*//3.2.成功 - 登录成功 - 生成token(uuid)  - 保存到redis - 30分钟
                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                Map<String, Object> map = new HashMap<>();
                map.put("token",token);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);*/

                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return map;

            }
        }
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        // 替换GET_ACK_URL指定的值
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        // 使用HttpUtil发送请求将GET_ACK_URL转为json字符串
        String jsonStr = HttpUtil.httpGet(url);
        // 将json字符串转为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 根据json对象中获取到的openid去查找wxuser对象
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (wxuser != null && wxuser.getUserId() != null){
            // 通过userid获取user对象
            User user = userMapper.findById(wxuser.getUserId());
            if (user != null){
                // 通过logininfoId获取logininfo对象
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        // 如果没有绑定前端就跳转到绑定页面
        String params = "?accessToken=" + accessToken + "&openId=" + openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");

        // 判断手机和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空！");
        }
        // 判断手机验证码是否过期/正确
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if (codeObj == null){
            throw new BusinessException("手机验证码过期！");
        }
        if (!codeObj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误！");
        }

        // 将GET_USER_URL数据替换，然后转为json格式得到json字符串
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);

        // 处理json字符串转为json对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr);

        // 根据phone查询user对象
        User user = userMapper.findByPhone(phone);
        // 判断user是否不存在
        if (user == null){
            // 如果不存在就通过phone创建一个user对象，同步保存到user表和logininfo表
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        // 将user的id设置到wxuser对象中
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        // 免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(result);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("logininfo",logininfo);
        //封装成一个LoginData对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);

        if (logininfo.getType() == 0){
            //1.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有菜单
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId());
            //2.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            loginData.setMenus(menus);
            loginData.setPermissions(permissions);
            map.put("menus",menus);
            map.put("permissions",permissions);
        }

        try {
            //3.获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //4.通过私钥对LoginData对象进行加密，加密成jwt字符串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);
            //5.将以上四个信息：logininfo，所有菜单，所有权限，jwtToken都要封装到Map进行返回 - 最终返回给前端
            //a.logininfo 返回给前端 - 回显信息
            //b.jwtToken 返回给前端 - 登陆权限
            //c.所有菜单  返回给前端 - 动态路由 - 实现动态菜单
            //d.所有权限  返回给前端 - 资源权限
            //疑问：jwtToken有这三个信息，但是需要解密 - but我们的前端没有解码。所以才要将logininfo，所有菜单，所有权限传递给前端
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String address = jsonObject.getString("country")
                + jsonObject.getString("province")
                + jsonObject.getString("city");
        wxuser.setAddress(address);
        return wxuser;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(4);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setPassword(md5Pwd);
        user.setSalt(salt);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }
}
